package com.spark.demoim.widget

import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import org.jetbrains.anko.*
import android.widget.LinearLayout
import android.graphics.drawable.Drawable
import android.view.ViewManager
import android.widget.ImageView
import android.widget.TextView
import com.spark.demoim.global.App
import org.jetbrains.anko.custom.ankoView
import java.util.*


@Suppress("DEPRECATED_IDENTITY_EQUALS")
/**
 * Created by lenovo on 2017/8/15.
 */
class TitleBar : ViewGroup, View.OnClickListener {
    constructor(ctx: Context) : super(ctx)

    constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs)

    constructor(ctx: Context, attrs: AttributeSet, defStyleAttr: Int) : super(ctx, attrs, defStyleAttr)

    companion object {
        private val DEFAULT_CENTER_TEXT_SIZE = 18
        private val DEFAULT_SUB_TEXT_SIZE = 14
        private val DEFAULT_HEIGHT = 48
    }

    val screenWidth by lazy { context.resources.displayMetrics.widthPixels }
    val statusBarHeight by lazy {
        resources.getDimensionPixelSize(
                resources.getIdentifier("status_bar_height", "dimen", "android"))
    }
    var titlebarHeight = 0
    var leftPadding = 10
    var titleBarPadding = 10
    var centerTitle = ""
    var centerSubTitle = ""
    var titleViewTextColor = 0

    val lp = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT)
    // 左边layout
    var leftContainer: LinearLayout? = null
    // 左文字
    var leftText: TextView? = null
    // 中间layout
    var centerContainer: LinearLayout? = null
    // 中间文字
    var centerText: TextView? = null
    // 中间子文字
    var centerSubText: TextView? = null
    // 右边layout
    var rightContainer: LinearLayout? = null
    // 分割线
    var divider: View? = null
    // 自定义中间view
    var customCenterView = view()

    init {
        titlebarHeight = dip(DEFAULT_HEIGHT)

        leftContainer = LinearLayout(context)

        leftText = TextView(context)
        leftText!!.textSize = DEFAULT_SUB_TEXT_SIZE.toFloat()
        leftText!!.singleLine = true
        leftText!!.gravity = Gravity.CENTER_VERTICAL
        leftText!!.setPadding(leftPadding + titleBarPadding, 0, leftPadding, 0)

        centerContainer = LinearLayout(context)
        centerContainer!!.gravity = Gravity.CENTER

        centerText = TextView(context)
        centerText!!.textSize = DEFAULT_CENTER_TEXT_SIZE.toFloat()
        centerText!!.singleLine = true
        centerText!!.gravity = Gravity.CENTER
        centerText!!.ellipsize = TextUtils.TruncateAt.END
        centerText!!.text = centerTitle

        centerSubText = TextView(context)
        centerSubText!!.textSize = DEFAULT_SUB_TEXT_SIZE.toFloat()
        centerSubText!!.singleLine = true
        centerSubText!!.gravity = Gravity.CENTER
        centerSubText!!.ellipsize = TextUtils.TruncateAt.END

        rightContainer = LinearLayout(context)
        rightContainer!!.setPadding(titleBarPadding, 0, titleBarPadding, 0)

        divider = View(context)

        addView(leftContainer, lp)
        addView(centerContainer)
        addView(rightContainer, lp)
        addView(divider, LayoutParams(LayoutParams.MATCH_PARENT, 1))
    }

    /**
     * layout
     */
    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        leftText!!.layout(0, statusBarHeight, leftText!!.measuredWidth, leftText!!.measuredHeight + statusBarHeight)
        rightContainer!!.layout(screenWidth - rightContainer!!.measuredWidth, statusBarHeight, screenWidth, rightContainer!!.measuredHeight + statusBarHeight)
        if (leftText!!.measuredWidth > rightContainer!!.measuredWidth) {
            centerContainer!!.layout(leftText!!.measuredWidth, statusBarHeight, screenWidth - leftText!!.measuredWidth, measuredWidth)
        } else {
            centerContainer!!.layout(rightContainer!!.measuredWidth, statusBarHeight, screenWidth - rightContainer!!.measuredWidth, measuredHeight)
        }
        divider!!.layout(0, measuredHeight - divider!!.measuredHeight, measuredWidth, measuredHeight)
    }

    /**
     * Measure
     */
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        var height = 0
        var myHeightMeasureSpec = heightMeasureSpec
        if (heightMode != View.MeasureSpec.EXACTLY) {
            height = titlebarHeight + statusBarHeight
            myHeightMeasureSpec = MeasureSpec.makeMeasureSpec(titlebarHeight, View.MeasureSpec.EXACTLY)
        } else {
            //height = MeasureSpec.getSize(myHeightMeasureSpec) + statusBarHeight
        }

        measureChild(leftText!!, widthMeasureSpec, myHeightMeasureSpec)
        measureChild(rightContainer!!, widthMeasureSpec, myHeightMeasureSpec)

        if (leftText!!.measuredWidth > rightContainer!!.measuredWidth) {
            centerContainer!!.measure(
                    MeasureSpec.makeMeasureSpec(screenWidth - 2 * leftText!!.measuredWidth, MeasureSpec.EXACTLY), myHeightMeasureSpec)
        } else {
            centerContainer!!.measure(
                    MeasureSpec.makeMeasureSpec(screenWidth - 2 * rightContainer!!.measuredWidth, MeasureSpec.EXACTLY), myHeightMeasureSpec)
        }
        measureChild(divider, widthMeasureSpec, myHeightMeasureSpec)
        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), height)
    }

    /**
     * titlebar 高度
     */
    fun settitlebarHeight(height: Int) {
        this.titlebarHeight = height
        setMeasuredDimension(measuredWidth, titlebarHeight)
    }

    /**
     * 左文字点击
     */
    fun setLeftClickListener(listener: OnClickListener) {
        leftText!!.setOnClickListener(listener)
    }

    /**
     * 左文字
     */
    fun setLeftText(text: CharSequence) {
        leftText!!.text = text
    }

    /**
     * 左文字
     */
    fun setLeftText(resid: Int) {
        leftText!!.setText(resid)
    }

    /**
     * 左文字大小
     */
    fun setLeftTextSize(size: Float) {
        leftText!!.textSize = size
    }

    /**
     * 左文字颜色
     */
    fun setLeftTextColor(color: Int) {
        leftText!!.textColor = color
    }

    /**
     * 左文字背景
     */
    fun setLeftTextBackground(drawable: Drawable) {
        leftText!!.backgroundDrawable = drawable
    }

    /**
     * 左文字可见
     */
    fun setLeftTextVisibile(visible: Boolean) {
        if (visible) {
            leftText!!.visibility = View.VISIBLE
        } else {
            leftText!!.visibility = View.GONE
        }
    }

    /**
     * 设置标题，如果有 \n 则设置子标题 vertical，如果有 \t 则设置子标题 horizontal
     */
    fun setTitle(title: CharSequence) {
        var index = title.toString().indexOf("\n")
        if (index > 0) {
            setCenterAndSubTitleWithOrientation(title.subSequence(0, index), title.subSequence(index + 1, title.length), LinearLayout.VERTICAL)
        } else {
            index = title.toString().indexOf("\t")
            if (index > 0) {
                setCenterAndSubTitleWithOrientation(title.subSequence(0, index), "  " + title.subSequence(index + 1, title.length), LinearLayout.HORIZONTAL)
            } else {
                centerText!!.text = title
                centerSubText!!.visibility = View.GONE
            }
        }
    }

    /**
     * 标题和子标题 以及方向
     */
    private fun setCenterAndSubTitleWithOrientation(title: CharSequence, subTitle: CharSequence, orientation: Int) {
        centerContainer!!.orientation = orientation
        centerText!!.text = title

        centerSubText!!.text = subTitle
        centerSubText!!.visibility = View.VISIBLE
    }

    /**
     * 标题点击事件
     */
    fun setCenterClickListener(listener: OnClickListener) {
        centerContainer!!.setOnClickListener(listener)
    }

    /**
     * 标题文字
     */
    fun setTitle(strRes: Int) {
        setTitle(resources.getString(strRes))
    }

    /**
     * 标题颜色
     */
    fun setTitleColor(resid: Int) {
        centerText!!.setTextColor(resid)
    }

    /**
     * 标题大小
     */
    fun setTitleSize(size: Float) {
        centerText!!.setTextSize(size)
    }

    /**
     * 标题背景
     */
    fun setCenterTitleBackground(resid: Int) {
        centerText!!.setBackgroundResource(resid)
    }

    /**
     * 子标题颜色
     */
    fun setSubTitleColor(resid: Int) {
        centerSubText!!.setTextColor(resid)
    }

    /**
     * 子标题大小
     */
    fun setSubTitleSize(size: Float) {
        centerSubText!!.setTextSize(size)
    }

    /**
     * 自定义标题
     */
    fun setCustomTitle(titleView: View?) = if (titleView == null) {
        centerText!!.setVisibility(View.VISIBLE)
        centerContainer!!.removeView(customCenterView)
    } else {
        if (customCenterView != null) {
            centerContainer!!.removeView(customCenterView)
        }
        val layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
        customCenterView = titleView
        centerContainer!!.addView(titleView, layoutParams)
        centerText!!.setVisibility(View.GONE)
    }

    /**
     * 设置分割线
     */
    fun setDivider(drawable: Drawable) {
        divider!!.setBackgroundDrawable(drawable)
    }

    /**
     * 分割线颜色
     */
    fun setDividerColor(color: Int) {
        divider!!.setBackgroundColor(color)
    }

    /**
     * 分隔线高度
     */
    fun setDividerHeight(dividerHeight: Int) {
        divider!!.getLayoutParams().height = dividerHeight
    }

    /**
     * TitleView 的点击事件
     */
    override fun onClick(view: View) {
        val tag = view.tag
        if (tag is TitleView) {
            tag.clicked(view)
        }
    }

    /**
     * 添加titleView List
     */
    fun addTitleViewList(titleList: LinkedList<TitleView>) {
        titleList.forEach {
            titleViewList.add(it)
        }
    }

    val titleViewList = LinkedList<TitleView>()
    /**
     * 在 Pos 位置添加 titleview
     */
    fun addTitleViewAtPos(action: TitleView, index: Int): View {
        val params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT)
        val view = addTitleView(action)
        rightContainer!!.addView(view, index, params)
        return view
    }

    /**
     * 移除所有 RightTitleView
     */
    fun removeAllRightTitleView() {
        rightContainer!!.removeAllViews()
    }

    /**
     * 移除 RightTitleLayout pos 位置的子控件
     */
    fun removeRightTitleViewAt(index: Int) {
        rightContainer!!.removeViewAt(index)
    }

    /**
     * 移除 rightTitLeLayout 中的子控件
     */
    fun removeRightTitleView(title: TitleView) {
        val childCount = rightContainer!!.childCount
        for (i in 0..childCount - 1) {
            val view = rightContainer!!.getChildAt(i)
            if (view != null) {
                val tag = view.tag
                if (tag != null && tag is TitleView && tag == title) {
                    rightContainer!!.removeView(view)
                }
            }
        }
    }

    /**
     * 获取 RightTitleLayout 子控件数目
     */
    fun getRightTitleCount(): Int {
        return rightContainer!!.childCount
    }

    /**
     * 添加TitleView
     */
    fun addTitleView(titleView: TitleView): View {
        var view: View?
        if (TextUtils.isEmpty(titleView.getText())) {
            val img = ImageView(context)
            img.setImageResource(titleView.getDrawableRes())
            view = img
        } else {
            val text = TextView(context)
            text.gravity = Gravity.CENTER
            text.setText(titleView.getText())
            text.textSize = DEFAULT_CENTER_TEXT_SIZE.toFloat()
            if (0 !== titleViewTextColor) {
                text.setTextColor(titleViewTextColor)
            }
            view = text
        }
        view.setPadding(dip(5), 0, dip(5), 0)
        view.tag = titleView
        view.setOnClickListener(this)
        return view
    }

    /**
     * 带文字，图标及点击时间的View
     */
    open interface TitleView {
        fun getText(): String?
        fun getDrawableRes(): Int
        fun clicked(v: View)
    }

    /**
     * ImageTitleView
     */
    open abstract class ImageTitleView(val drawable: Int) : TitleView {
        override fun getDrawableRes(): Int {
            return drawable
        }

        override fun getText(): String? {
            return null
        }
    }

    /**
     * TextTitleView
     */
    open abstract class TextTitleView(val name: String) : TitleView {
        override fun getDrawableRes(): Int {
            return 0
        }

        override fun getText(): String? {
            return name
        }
    }
}

/*
*
 * 使用 DSL 语言描述TitleBar
inline fun ViewManager.titleBar() = TitleBar(App.appContext!!)

inline fun ViewManager.titleBar(init: TitleBar.() -> Unit): TitleBar {
    return ankoView({ TitleBar(App.appContext!!) }, 0, init)
}*/
